package org.xhy.aop.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.xhy.aop.annotation.Aop;
import org.xhy.aop.core.ProxyFactory;

import java.util.HashMap;
import java.util.Map;


@Component
public class PointBeanPostProcess implements BeanPostProcessor {


    // 需要路径切入点的bean
    Map<String,Object> jointPointPathMap;

    Map<Class,Object> jointPointAnnotationMap;

    public PointBeanPostProcess(){
        jointPointPathMap = new HashMap<>();
        jointPointAnnotationMap = new HashMap<>();
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        final Class<?> beanClass = bean.getClass();
        final Aop aop = beanClass.getAnnotation(Aop.class);
        if (aop!=null) {
            final String jointPath = aop.jointPath();
            // 两个中只能生效一个
            if (!jointPath.equals("")){
                jointPointPathMap.put(jointPath,bean);
            }else {
                jointPointAnnotationMap.put(aop.joinAnnotationClass(),bean);
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        final Class<?> beanClass = bean.getClass();
        final String path = beanClass.getName();
        // match
        for (String s : jointPointPathMap.keySet()) {
            if (path.startsWith(s)){
                return ProxyFactory.tryBuild(bean, jointPointPathMap.get(s));
            }
        }
        for (Object aopObject : jointPointAnnotationMap.values()) {
            return ProxyFactory.tryBuild(bean, aopObject);
        }
        return bean;
    }
}
